from nicegui import ui
import plotly.graph_objects as go

# 存储所有点的列表
points = []

# 创建输入框
x_input = ui.input(label='X坐标').classes('w-32')
y_input = ui.input(label='Y坐标').classes('w-32')
z_input = ui.input(label='Z坐标').classes('w-32')

# 创建按钮容器
with ui.row():
    ui.button('添加点', on_click=lambda: add_point()).classes('bg-green-200')
    ui.button('删除点', on_click=lambda: remove_point()).classes('bg-red-200')

# 图表容器
plot_container = ui.row()


def add_point():
    try:
        # 获取并验证输入
        x = float(x_input.value)
        y = float(y_input.value)
        z = float(z_input.value)
    except ValueError:
        ui.notify('请输入有效的数字', color='negative')
        return

    new_point = (x, y, z)

    # 检查点是否已存在
    if new_point in points:
        ui.notify('该点已存在', color='warning')
        return

    points.append(new_point)
    update_plot()
    ui.notify(f'成功添加点 ({x}, {y}, {z})', color='positive')


def remove_point():
    try:
        # 获取并验证输入
        x = float(x_input.value)
        y = float(y_input.value)
        z = float(z_input.value)
    except ValueError:
        ui.notify('请输入有效的数字', color='negative')
        return

    target = (x, y, z)

    if target in points:
        points.remove(target)
        update_plot()
        ui.notify(f'成功删除点 ({x}, {y}, {z})', color='positive')
    else:
        ui.notify(f'点 ({x}, {y}, {z}) 不存在', color='negative')


def update_plot():
    # 清除旧图表
    plot_container.clear()

    # 创建新图表
    with plot_container:
        if points:
            # 提取坐标数据
            x = [p[0] for p in points]
            y = [p[1] for p in points]
            z = [p[2] for p in points]

            # 创建三维散点图
            fig = go.Figure(data=[go.Scatter3d(
                x=x,
                y=y,
                z=z,
                mode='markers',
                marker=dict(
                    size=8,
                    color=z,  # 使用Z值作为颜色
                    colorscale='Viridis'
                )
            )])

            # 设置布局
            fig.update_layout(
                scene=dict(
                    xaxis_title='X',
                    yaxis_title='Y',
                    zaxis_title='Z'
                ),
                margin=dict(l=0, r=0, b=0, t=30),
                height=600
            )

            ui.plotly(fig)
        else:
            ui.label('暂无数据，请添加点').classes('text-gray-500')


# 初始化时更新图表
update_plot()

ui.run(title='三维点云编辑器', port=8080)